<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-button type="primary"> 添加按钮 </el-button>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', index1 == 0 ? 'bdtop' : '', 'vcenter', 'm_l']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row v-for="(item2, index2) in item1.children" :key="item2.id" :class="[index2 == 0 ? '' : 'bdtop', 'vcenter']">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightById(scope.row, item2)">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag closable type="warning" v-for="(item3, index3) in item2.children" :key="item3.id" @close="removeRightById(scope.row, item3)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="level" label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
        ></el-table
      >
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="权限分配" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <el-tree :data="rightList" show-checkbox node-key="id" :props="treeProps" :default-expand-all="true" :default-checked-keys="defaultKeys" ref="treeRef"> </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogClosed">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框中的树形结构 -->
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      rolesList: [],
      setRightDialogVisible: false,
      treeProps: { children: 'children', label: 'authName' },
      rightList: [],
      defaultKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.rolesList = res.data
    },
    // 根据Id删除对应的权限
    async removeRightById(role, right) {
      const a = await this.$confirm('是否确定删除该权限?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (a == 'cancel') return this.$message.info('取消成功')
      if (a == 'confirm') {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${right.id}`)
        if (res.meta.status !== 200) return this.$message.info(res.meta.msg)
        role.children = res.data
      }
    },
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.rightList = res.data
      this.getLeafKeys(role, this.defaultKeys)
      this.setRightDialogVisible = true
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.setRightDialogVisible = false
      this.defaultKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status != 200) return $this.$message.error('角色分配权限失败')
      this.$message.success('分配角色权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    // 通过递归的形式获取该角色下所有三级权限的ID，并保存到数组中
    getLeafKeys(node, arr) {
      // 如果当前node节点没有children，则为三级权限节点
      if (!node.children) {
        return arr.push(node.id)
      } else {
        node.children.forEach(item => {
          this.getLeafKeys(item, arr)
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.m_l {
  margin-left: 50px;
}
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
